const express = require('express');
const router = express.Router();
const { projectPhaseModel } = require('../db/projectPhase');

// 获取项目阶段列表
router.get('/list', async (req, res) => {
    try {
        const { page = 1, limit = 10, status, search } = req.query;
        const skip = (page - 1) * limit;
        
        // 构建查询条件
        let query = {};
        if (status) query.status = status;
        if (search) {
            query.$or = [
                { phase: { $regex: search, $options: 'i' } },
                { leader: { $regex: search, $options: 'i' } }
            ];
        }
        
        // 查询数据
        const phases = await projectPhaseModel.find(query)
            .sort({ createTime: -1 })
            .skip(skip)
            .limit(parseInt(limit));
        
        // 获取总数
        const total = await projectPhaseModel.countDocuments(query);
        
        res.json({
            success: true,
            data: phases,
            total,
            page: parseInt(page),
            limit: parseInt(limit)
        });
    } catch (error) {
        console.error('获取项目阶段列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取项目阶段列表失败',
            error: error.message
        });
    }
});

// 获取单个项目阶段详情
router.get('/detail/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const phase = await projectPhaseModel.findOne({ id: parseInt(id) });
        
        if (!phase) {
            return res.status(404).json({
                success: false,
                message: '项目阶段不存在'
            });
        }
        
        res.json({
            success: true,
            data: phase
        });
    } catch (error) {
        console.error('获取项目阶段详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取项目阶段详情失败',
            error: error.message
        });
    }
});

// 创建项目阶段
router.post('/create', async (req, res) => {
    try {
        const phaseData = req.body;
        
        // 获取最大ID
        const maxPhase = await projectPhaseModel.findOne().sort({ id: -1 });
        const newId = maxPhase ? maxPhase.id + 1 : 1;
        
        // 创建新阶段
        const newPhase = new projectPhaseModel({
            ...phaseData,
            id: newId,
            createTime: new Date(),
            updateTime: new Date()
        });
        
        await newPhase.save();
        
        res.json({
            success: true,
            message: '项目阶段创建成功',
            data: newPhase
        });
    } catch (error) {
        console.error('创建项目阶段失败:', error);
        res.status(500).json({
            success: false,
            message: '创建项目阶段失败',
            error: error.message
        });
    }
});

// 更新项目阶段
router.put('/update/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const updateData = req.body;
        
        const phase = await projectPhaseModel.findOneAndUpdate(
            { id: parseInt(id) },
            { ...updateData, updateTime: new Date() },
            { new: true }
        );
        
        if (!phase) {
            return res.status(404).json({
                success: false,
                message: '项目阶段不存在'
            });
        }
        
        res.json({
            success: true,
            message: '项目阶段更新成功',
            data: phase
        });
    } catch (error) {
        console.error('更新项目阶段失败:', error);
        res.status(500).json({
            success: false,
            message: '更新项目阶段失败',
            error: error.message
        });
    }
});

// 删除项目阶段
router.delete('/delete/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        const phase = await projectPhaseModel.findOneAndDelete({ id: parseInt(id) });
        
        if (!phase) {
            return res.status(404).json({
                success: false,
                message: '项目阶段不存在'
            });
        }
        
        res.json({
            success: true,
            message: '项目阶段删除成功'
        });
    } catch (error) {
        console.error('删除项目阶段失败:', error);
        res.status(500).json({
            success: false,
            message: '删除项目阶段失败',
            error: error.message
        });
    }
});

// 批量删除项目阶段
router.delete('/batch-delete', async (req, res) => {
    try {
        const { ids } = req.body;
        
        if (!ids || !Array.isArray(ids)) {
            return res.status(400).json({
                success: false,
                message: '请提供要删除的ID列表'
            });
        }
        
        const result = await projectPhaseModel.deleteMany({ id: { $in: ids } });
        
        res.json({
            success: true,
            message: `成功删除 ${result.deletedCount} 个项目阶段`
        });
    } catch (error) {
        console.error('批量删除项目阶段失败:', error);
        res.status(500).json({
            success: false,
            message: '批量删除项目阶段失败',
            error: error.message
        });
    }
});

// 更新项目阶段状态
router.put('/update-status/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { status, statusType } = req.body;
        
        const phase = await projectPhaseModel.findOneAndUpdate(
            { id: parseInt(id) },
            { 
                status, 
                statusType, 
                updateTime: new Date(),
                // 如果状态为已完成，设置实际完成时间
                ...(status === '已完成' && { realEndTime: new Date() })
            },
            { new: true }
        );
        
        if (!phase) {
            return res.status(404).json({
                success: false,
                message: '项目阶段不存在'
            });
        }
        
        res.json({
            success: true,
            message: '项目阶段状态更新成功',
            data: phase
        });
    } catch (error) {
        console.error('更新项目阶段状态失败:', error);
        res.status(500).json({
            success: false,
            message: '更新项目阶段状态失败',
            error: error.message
        });
    }
});

// 获取项目阶段统计信息
router.get('/stats', async (req, res) => {
    try {
        const stats = await projectPhaseModel.aggregate([
            {
                $group: {
                    _id: '$status',
                    count: { $sum: 1 }
                }
            }
        ]);
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取项目阶段统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取项目阶段统计失败',
            error: error.message
        });
    }
});

module.exports = router; 